package com.hmall.item.mq;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * TODO
 *
 * @Author wangxinyi
 * @Date 2024/11/15 19:58
 */
@Component
public class SpringRabbitListener {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = "item.queue")
    public void simpleListener(String msg) {
        //更新缓存
        //从数据库中查出前20位销量高的商品，从高到低
        if (msg != null) {
            String key = "HotSold::";
            LambdaQueryWrapper<Item> lqw = new LambdaQueryWrapper<>();
            lqw.orderByDesc(Item::getSold).last("limit 20");
            List<Item> itemList = itemMapper.selectList(lqw);
            //采用String存储结构,value为itemList
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(itemList));
        }
    }
}
